Page({
  data: {
    history: [],
    searchQuery: '',
    searchResults: null,
    hasResults: false
  },

  onLoad() {
    const history = wx.getStorageSync('searchHistory') || [];
    this.setData({ history });
  },

  onInput(event) {
    this.setData({ searchQuery: event.detail.value });
  },

  onSearch() {
    const query = this.data.searchQuery.trim();
    if (query) {
      this.searchAll(query);
      this.addToHistory(query);
    }
  },

  onHistoryItemTap(event) {
    const query = event.currentTarget.dataset.query;
    this.setData({ searchQuery: query });
    this.searchAll(query);
  },

  clearHistory() {
    this.setData({ 
      history: [], 
      searchResults: null, 
      hasResults: false 
    });
    wx.setStorageSync('searchHistory', []);
  },

  addToHistory(query) {
    let history = this.data.history;
    const index = history.indexOf(query);
    if (index > -1) {
      history.splice(index, 1);
    }
    history.unshift(query);
    history = history.slice(0, 10);
    this.setData({ history });
    wx.setStorageSync('searchHistory', history);
  },

  searchAll(query) {
    this.setData({ searchResults: null, hasResults: false });
    wx.showLoading({ title: '搜索中...' });
    wx.request({
      url: 'http://localhost:8080/api/search/all',
      data: { query },
      success: (res) => {
        wx.hideLoading();
        console.log('API response:', res);
        if (res.statusCode === 200 && res.data) {
          const searchResults = res.data;
          const categories = ['experts', 'articles', 'questions', 'tests', 'courses'];
          const filteredResults = {};
          let hasResults = false;

          categories.forEach(category => {
            if (Array.isArray(searchResults[category]) && searchResults[category].length > 0) {
              filteredResults[category] = searchResults[category];
              hasResults = true;
            }
          });

          console.log('Filtered results:', filteredResults);
          console.log('Has results:', hasResults);

          this.setData({
            searchResults: filteredResults,
            hasResults
          });

          if (!hasResults) {
            wx.showToast({
              title: '没有找到相关结果',
              icon: 'none'
            });
          }
        } else {
          console.log('Unexpected response structure:', res);
          this.setData({ searchResults: null, hasResults: false });
          wx.showToast({
            title: '搜索结果异常',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('搜索请求错误:', err);
        this.setData({ searchResults: null, hasResults: false });
        wx.showToast({
          title: '网络错误，请检查网络连接',
          icon: 'none'
        });
      }
    });
  },

  viewAllExperts() {
    this.navigateToSearchPage('expert');
  },

  viewAllArticles() {
    this.navigateToSearchPage('article');
  },

  viewAllQuestions() {
    this.navigateToSearchPage('question');
  },

  viewAllTests() {
    this.navigateToSearchPage('test');
  },

  viewAllCourses() {
    this.navigateToSearchPage('course');
  },

  navigateToSearchPage(type) {
    wx.navigateTo({
      url: `/pages/index/search/search-${type}/search-${type}?query=${this.data.searchQuery}`
    });
  }
});